package com.concurrent.sample.business.event.listener;

import com.concurrent.sample.business.event.listener.event.ExternalOrderExecReportEvent;
import com.concurrent.sample.business.event.param.trade.TradeExecReportDTO;
import com.concurrent.sample.business.common.consts.BusinessNatsConsts;
import com.concurrent.sample.common.nats.NatsConnFactory;
import com.concurrent.sample.common.nats.NatsProperties;
import com.concurrent.sample.common.util.JsonUtils;
import io.nats.client.Connection;
import io.nats.client.Dispatcher;
import java.nio.charset.StandardCharsets;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class ExternalOrderExecReportNatsListener implements ApplicationRunner {

  private final NatsProperties natsProperties;

  private final ApplicationEventPublisher eventPublisher;

  @Override
  public void run(ApplicationArguments args) throws Exception {
    log.info("order exec report nats listener start");
    Connection nc = NatsConnFactory.getSingle(natsProperties);

    Dispatcher d = nc.createDispatcher((msg) -> {});

    d.subscribe(BusinessNatsConsts.TRADE_EXEC_REPORT_TOPIC, (msg) -> {
      String response = new String(msg.getData(), StandardCharsets.UTF_8);

      TradeExecReportDTO execReport = JsonUtils.fromJson(TradeExecReportDTO.class, response);
      log.info("received nats message, order exec report content = {}", execReport);

      eventPublisher.publishEvent(new ExternalOrderExecReportEvent(this, execReport));
    });
  }

}
